<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
		<meta content="yes" name="apple-mobile-web-app-capable" />
		<meta content="black" name="apple-mobile-web-app-status-bar-style" />
		<meta content="telephone=no" name="format-detection" />
		<meta content="email=no" name="format-detection" />
		<title>寻找设备</title>
		<link rel="stylesheet" href="../../css/s_plus.css" />
		<link rel="stylesheet" href="../../css/base.css" />
		<link rel="stylesheet" href="../../css/layout.css" />
		<link rel="stylesheet" href="../../css/choice.css" />
		<link rel="stylesheet" href="../../css/hui.css" />

		<script type="text/javascript" src="../../libs/vue.js"></script>
		<script type="text/javascript" src="../../js/jquery.1.9.1.min.js"></script>
		<script type="text/javascript" src="../../js/app/url.js"></script>
		<script type="text/javascript" src="../../js/mui.min.js"></script>

		<script type="text/javascript" src="../../libs/hui.js"></script>
		<script type="text/javascript" src="../../js/app/api.js?time=20181261"></script>
		<script type="text/javascript" src="../../js/control/pop.js"></script>
		<script type="text/javascript" src="../../js/md5.js"></script>
		<script type="text/javascript" src="../../js/app/ble.js"></script>


	</head>

	<body>
		<div id="wrapper">
			<header class="f_l maxbox subhead">
				<a class="back" @click="back"><i class="iconfont">&#xe605;</i></a>
				<h1>寻找附近设备</h1>
			</header>
			<section class="f_l maxbox unlock">
				<ul>
					<li>
						<b class="f_l gray">附近设备列表</b>
						<a class="f_r" @click="getBleList"><i class="iconfont orange">&#xe61a;</i></a>
					</li>
					<li v-for="(ble,index)  in bleList" @click="goSetting(ble.isConnected)">
						<p class="radio radio_success">
							<input name="choice1" type="radio" value="option1">
							<label for="radio1">{{ble.name}}({{ble.mac}})</label>
						</p>
						<div class="state">
							<!--{{ble.rssi}}-->
							<button @click="ble.isConnected==1?disconnectBle(ble.mac,index) :connectBle(ble.mac,index)" class="hui-button hui-button-small search" v-text=" ble.isConnected==1?'断开连接':'连接'"></button>
						</div>

					</li>

				</ul>
			</section>

		</div>

		<script>
			var bleConnect;
			
			

 			var BAdapter;
			mui.plusReady(function() {
				 var main = plus.android.runtimeMainActivity();
			    var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
			     BAdapter = new BluetoothAdapter.getDefaultAdapter();
			    if (!BAdapter.isEnabled()) {
//			    	hui.toast("请开启蓝牙");
			        BAdapter.enable(); //启动蓝牙
			    }else{
//			        BAdapter.disable();
			    }
				
				bleConnect = plus.blecontroler;
				//扫描前初始化蓝牙
				var returnStr = bleConnect.init();
				vm.getBleList();
				
			});

			var vm = new Vue({
				el: "#wrapper",
				data: {
					isReport:false,
					p_mac: "",
					bleList: [],
					connectedDevice: null, //连接的设备
					notifyList: [], //通知列表
					Tid: "", //终端编号
				},
				mounted: function() {


				},

				methods: {
					goSetting: function(param) {

						if(param == '1') {

							console.log("跳转前:--- " + this.Tid);
							console.log("跳转前:--- " + this.p_mac);

							localStorage.setItem("zd_id", this.Tid);
							localStorage.setItem("mac", this.p_mac);

				var type = localStorage.getItem("type");
					if(type == 'baozhuang') {
//							alert("type--"+type);
							localStorage.setItem("pid", this.Tid);
							localStorage.setItem("zd_id", this.Tid);
							localStorage.setItem("mac", this.p_mac);
//							localStorage.setItem("type", "baozhuang");
							if(this.Tid==null||this.Tid==''){
								hui.toast("请重新连接设备获取终端ID");
								return;
							}
							hui.open("/modules/alerm/sensor_data.html?time" + apiManage.getNow(), {}, true, {});
					
					return;	
					}

  							if(this.Tid==null||this.Tid==''){
  								hui.toast("获取终端ID失败，请重新连接设备获取!");
  								return;
  							}
							hui.open("setting.html?time=" + apiManage.getNow(), {}, true, {Tid:this.Tid});

						} else {

						}
					},
					back: function() {
						console.log("this.connectedDevice-" + this.connectedDevice);
						if(this.connectedDevice != null) {
							var readyBlockMac = this.connectedDevice.mac;
							bleConnect.disconnectBle(readyBlockMac);
						}

						bleConnect.destory();
						hui.back();

					},
					getBleList: function() {
						//					alert('22');
						if(!window.plus) {
							alert("请在H5+环境中使用!");
							return;
						}
						
						if(!BAdapter.isEnabled()){
							hui.toast("请开启蓝牙设置");
							return;
						}

						var _self = this;

						if(this.connectedDevice != null) {
							var readyBlockMac = this.connectedDevice.mac;
							bleConnect.disconnectBle(readyBlockMac);
						}

						//						hui.loading("正在搜索蓝牙设备...");
						//3243
						var deviceName = ""; //指定蓝牙设备名
						vm.bleList = [];
						//开始搜索蓝牙设备
						//						if(this.connectedDevice!=null){
						//							_self.bleList = _self.bleList.concat(this.connectedDevice);
						//						}
						bleConnect.scan(deviceName, function(sucess) {
							hui.closeLoading();
							console.log("搜索出来的-----" + sucess);
							var ret = JSON.parse(sucess);
							//							if(ret.state)!=null){
							//								return;
							//							}

							if(ret.state == 0) {

								//						if (ret.ble.name!=null){
								_self.bleList = _self.bleList.concat(ret.ble);
								//						}

							} else {
								hui.closeLoading();
								console.log("搜索完成");
							}
						}, function(err) {
							hui.closeLoading();
							//							alert(err);
							console.log(err);
						});

					},

					//连接设备
					connectBle: function(mac, index) {
						var _self = this;
						hui.loading("正在连接蓝牙设备...");
						vm.Tid="";
						bleConnect.connectBle(mac, function(ret) {
							console.log("连接蓝牙设备成功:" + ret);
							hui.closeLoading();
							hui.toast("连接蓝牙设备成功");
							//							setTimeout(1,getTid());
							//							getTid();
							console.log("mac----" + mac);
							vm.p_mac = mac;
							
							setTimeout(function() {
								getTid();
							}, 300);


							//							alert(ret);
							//							vm.bleList = JSON.parse(retList);
							//alert(sucess);
							_self.connectedDevice = _self.bleList[index];
							for(var i=0;i<_self.bleList.length;i++){//设置连接状态之前把其他设备状态重置
//								var cell=_self.bleList[i];
								_self.$set(_self.bleList[i], "isConnected", 0);
							}
							_self.$set(_self.bleList[index], "isConnected", 1);
						}, function(err) {
							hui.closeLoading();
							hui.toast("连接失败");
							//							console.log(err);
						});
					},

					disconnectBle: function(mac, index) {
						
						console.log("断开的mac----"+ mac);
						bleConnect.disconnectBle(mac);
					
											vm.Tid="";

						this.$set(this.bleList[index], "isConnected", 0);
						this.connectedDevice = null;
					},
				}
			});

			//获取终端编号
			function getTid() {
				//				alert('getTid');
				bleConnect.writeData("5A1008FFFFFFFFFFFFFFFF", function(ret) {
					console.log("返回数据:" + ret);
					//					var cell = JSON.parse(ret);
					
					if(!checkCommand(ret)){
						hui.toast("终端ID获取失败,请重连设备.");
						vm.Tid="";

						return;
					}
					if(ret.indexOf("state") != -1) {
						return;
					}
					vm.Tid = ret.substring(6, 22);
					//					localStorage.setItem("zd_id",vm.Tid);

					vm.notifyList = vm.notifyList.concat("获取终端: " + ret);

					console.log("终端ID: " + vm.Tid);

					if(vm.Tid!=null&&vm.Tid!=""){
							setTimeout(function() {
							loadDetail(vm.Tid);
						}, 500);
					}
					else{
						
							hui.toast("无法获取终端ID，请在设备列表选择本公司的终端！");

					}
					
				

				}, function(err) {
					hui.closeLoading();
					console.log(err);
					hui.toast("获取终端ID失败，请重新连接");
					vm.Tid="";
					
				});
			}

			//终端详情
			function loadDetail(zdCode) {
				hui.loading("终端信息加载中...");

				var username = localStorage.getItem("username");
				var sec = localStorage.getItem("sec_pwd");
				var time = apiManage.getNow();
				var key = "loginName=" + username + "&passWord=" + sec + "&time=" + time;
				var paramKey = hex_md5(key);
				var jsonParam = JSON.stringify({
					loginName: username,
					time: time,
					key: paramKey
				});

				console.log("jsonParam:  " + jsonParam);

				var path = urlManager.terminalDetail() + "?terminalCode=" + zdCode;
				//var path = urlManager.terminalDetail()+"?terminalCode=0143010201000003"

				console.log("path:  " + path);
				$.ajax({
					type: "GET",
					url: path,
					beforeSend: function(request) {
						request.setRequestHeader("loginName", username);
						request.setRequestHeader("time", time);
						request.setRequestHeader("sign", paramKey);
						request.setRequestHeader("Content-Type", "application/text");

					},
					success: function(result) {
						hui.closeLoading();
						console.log("终端详情:" + JSON.stringify(result));
						var myCustID = localStorage.getItem("companyId");
						myCustID = myCustID.trim();
						var zdCustId = "";
						if(result.termimalCode != null) {
							zdCustId = result.jgId.cusId;
							zdCustId = zdCustId.trim();
						}

						var type = localStorage.getItem("type");
//						alert(type);
						if(type == 'baozhuang') {
							localStorage.setItem("nosubmit", "no");

							if(result == "" || result == null) {
								
								localStorage.setItem("pid", zdCode);
//								localStorage.setItem("type", "baozhuang");
								
								hui.open("/modules/alerm/sensor_data.html?abc=99&time=" + apiManage.getNow(), {}, true, {});


							} else {
								vm.isReport=true;
								alert("终端已报装，不可重复操作。");
								
								return;


							}
						} else {



							localStorage.setItem("nosubmit", "yes");
							vm.goSetting('1');


						}

//						console.log("我的客户ID " + myCustID + "-  终端的客户ID " + result.jgId.cusId);
						hui.closeLoading();

					}

				});

			}
			
			
			//检查获取终端是否成功
			function checkCommand(command) {
				console.log("command.toUpperCase().indexOf('5a2008')"+  command.toUpperCase().indexOf('5a2008'));
				return command.toUpperCase().indexOf('5a2008') < 0;
			}
			
			loadCondition();
			
			//获取传感配置
				function loadCondition() {

				var username = localStorage.getItem("username");
				var sec = localStorage.getItem("sec_pwd");
				var time = apiManage.getNow();
				var key = "loginName=" + username + "&passWord=" + sec + "&time=" + time;
				var paramKey = hex_md5(key);
				var jsonParam = JSON.stringify({
					loginName: username,
					time: time,
					key: paramKey
				});

				console.log("jsonParam:  " + jsonParam);

				var path = urlManager.getAlarmruleCondition() ;
				//var path = urlManager.terminalDetail()+"?terminalCode=0143010201000003"

				console.log("path:  " + path);
				$.ajax({
					type: "GET",
					url: path,
					beforeSend: function(request) {
						request.setRequestHeader("loginName", username);
						request.setRequestHeader("time", time);
						request.setRequestHeader("sign", paramKey);
						request.setRequestHeader("Content-Type", "application/text");

					},
					success: function(result) {
//						hui.closeLoading();
						console.log("配置详情:--" + JSON.stringify(result));
					
					   localStorage.setItem("condition",JSON.stringify(result));//配置信息保存到缓存 便于存储

					}

				});

			}
		</script>
	</body>

</html>